package geektime.spring.springbucks;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

@EnableTransactionManagement
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
//引入xml配置
public class SpringBucksApplication implements ApplicationRunner {
     @Autowired
	RestTemplate restTemplate;

	public static void main(String[] args) {
		SpringApplication.run(SpringBucksApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		// 调用xml接口
		ResponseEntity<String> exchange = this.restTemplate.exchange("http://localhost:8080/getXmlCoffeeById/3", HttpMethod.GET, null, String.class);
		int statusCodeValue = exchange.getStatusCodeValue();
		String body = exchange.getBody();
		System.out.println(statusCodeValue);
		System.out.println(body);

		// 调用json接口
		System.out.println(RemoteInvoking("http://localhost:8080/getCoffeeById/3"));

	   //httpClient 调用
		System.out.println(getRequest("http://localhost:8080/getCoffeeById/3"));
	}

	public static String RemoteInvoking(String url) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url ;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public String getRequest(String url) throws URISyntaxException, IOException {
		//创建httpClient实例
		CloseableHttpClient client = HttpClients.createDefault();
		//创建一个uri对象
		URIBuilder uriBuilder = new URIBuilder(url);
		//创建httpGet远程连接实例,这里传入目标的网络地址
		HttpGet httpGet = new HttpGet(uriBuilder.build());
		// 设置配置请求参数(没有可忽略)
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
				.setConnectionRequestTimeout(35000)// 请求超时时间
				.setSocketTimeout(60000)// 数据读取超时时间
				.build();
		// 为httpGet实例设置配置
		httpGet.setConfig(requestConfig);
		//执行请求
		CloseableHttpResponse response = client.execute(httpGet);
		//获取Response状态码
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		//获取响应实体, 响应内容
		HttpEntity entity = response.getEntity();
		//通过EntityUtils中的toString方法将结果转换为字符串
		String str = EntityUtils.toString(entity);
		response.close();
		client.close();
		return str;

	}
}

